/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FichaAnimal.java
 *
 * Created on 23-nov-2011, 17:57:58
 */
package formularios;

import clases.ConversorRSaDefaultTableModel;
import clases.LimpiarJTable;
import clases.conexion;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author CoLiSa
 */
public class FichaAnimal extends javax.swing.JDialog {

    /** Creates new form FichaAnimal */
    public FichaAnimal() {
        initComponents();
        this.setModal(true);
        completarcomboraza();
        completarcombopelaje();
        completarcomboprocedencia();
        completarcombotipo();
        completarcombocliente();
        completarcomboestado();
        completarcomboaños();
    }

    public FichaAnimal(String identificacion) {
        initComponents();
        this.setModal(true);
        completarcomboraza();
        completarcombopelaje();
        completarcomboprocedencia();
        completarcombotipo();
        completarcombocliente();
        completarcomboestado();
        completarcomboaños();
        txtbuscar.setText(identificacion);
        chequearid(identificacion);
        new Estadisticas(null, false).GenerarLineaCrecPeso(Integer.parseInt(identificacion), lblChart, tablaPeso);
        cargardatos();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        txtidentificacion = new javax.swing.JTextField();
        txtidsenasa = new javax.swing.JTextField();
        txtidtag = new javax.swing.JTextField();
        txtfechaaplicacion = new javax.swing.JTextField();
        combocolorcaravana = new javax.swing.JComboBox();
        combonacimiento = new javax.swing.JComboBox();
        txtedad = new javax.swing.JTextField();
        txtnumfuego = new javax.swing.JTextField();
        combosexo = new javax.swing.JComboBox();
        comboraza = new javax.swing.JComboBox();
        combopelaje = new javax.swing.JComboBox();
        comboprocedencia = new javax.swing.JComboBox();
        txtidmadre = new javax.swing.JTextField();
        combotipobovino = new javax.swing.JComboBox();
        combocliente = new javax.swing.JComboBox();
        comboestado = new javax.swing.JComboBox();
        txtpeso = new javax.swing.JTextField();
        jPanel6 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablavacunacion = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        lblChart = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaPeso = new javax.swing.JTable();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tablaenfermedades = new javax.swing.JTable();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        tablaobservaciones = new javax.swing.JTable();
        jLabel10 = new javax.swing.JLabel();
        txtbuscar = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ficha del Animal");
        setResizable(false);

        jPanel5.setLayout(new java.awt.GridLayout(17, 0, 5, 5));

        txtidentificacion.setEditable(false);
        jPanel5.add(txtidentificacion);
        jPanel5.add(txtidsenasa);

        txtidtag.setEditable(false);
        jPanel5.add(txtidtag);

        txtfechaaplicacion.setEditable(false);
        jPanel5.add(txtfechaaplicacion);

        combocolorcaravana.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Verde", "Naranja", "Amarillo", "Roja", "Blanca", "Celeste" }));
        combocolorcaravana.setSelectedIndex(-1);
        jPanel5.add(combocolorcaravana);

        combonacimiento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                combonacimientoActionPerformed(evt);
            }
        });
        jPanel5.add(combonacimiento);

        txtedad.setEditable(false);
        jPanel5.add(txtedad);
        jPanel5.add(txtnumfuego);

        combosexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Macho", "Hembra" }));
        combosexo.setSelectedIndex(-1);
        jPanel5.add(combosexo);

        jPanel5.add(comboraza);
        jPanel5.add(combopelaje);
        jPanel5.add(comboprocedencia);
        jPanel5.add(txtidmadre);

        jPanel5.add(combotipobovino);

        jPanel5.add(combocliente);

        jPanel5.add(comboestado);
        jPanel5.add(txtpeso);

        jPanel6.setLayout(new java.awt.GridLayout(17, 0, 5, 5));

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setText("Nº de Manejo");
        jPanel6.add(jLabel1);

        jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel16.setText("Identificación SENASA");
        jPanel6.add(jLabel16);

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("Identificación Electrónica");
        jPanel6.add(jLabel2);

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("Fecha de Aplicacion de Caravana");
        jPanel6.add(jLabel3);

        jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel17.setText("Color de la caravana");
        jPanel6.add(jLabel17);

        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel6.setText("Año de Nacimiento");
        jPanel6.add(jLabel6);

        jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel15.setText("Edad");
        jPanel6.add(jLabel15);

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel5.setText("Número de Fuego");
        jPanel6.add(jLabel5);

        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel4.setText("Sexo");
        jPanel6.add(jLabel4);

        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel7.setText("Raza");
        jPanel6.add(jLabel7);

        jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel8.setText("Pelaje");
        jPanel6.add(jLabel8);

        jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel9.setText("Procedencia");
        jPanel6.add(jLabel9);

        jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel11.setText("Identificacion de la  Madre");
        jPanel6.add(jLabel11);

        jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel12.setText("Tipo de Bovino");
        jPanel6.add(jLabel12);

        jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel13.setText("Cliente");
        jPanel6.add(jLabel13);

        jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel14.setText("Estado del Animal");
        jPanel6.add(jLabel14);

        jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel18.setText("Peso");
        jPanel6.add(jLabel18);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/filesave.png"))); // NOI18N
        jButton2.setText("Guardar Cambios");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(52, 52, 52)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton2)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(234, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton2)
                .addGap(155, 155, 155))
        );

        jTabbedPane1.addTab("Datos Generales", jPanel1);

        tablavacunacion.setAutoCreateRowSorter(true);
        tablavacunacion.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tablavacunacion);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 704, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 606, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Vacunaciones", jPanel2);

        tablaPeso.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(tablaPeso);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblChart, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 680, Short.MAX_VALUE))
                .addContainerGap(34, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblChart, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(66, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Control de Peso", jPanel3);

        tablaenfermedades.setAutoCreateRowSorter(true);
        tablaenfermedades.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane3.setViewportView(tablaenfermedades);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 704, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 606, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Historial de Enfermedades", jPanel4);

        tablaobservaciones.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane4.setViewportView(tablaobservaciones);

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 704, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 606, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Observaciones", jPanel7);

        jLabel10.setText("Ingresar el número de Manejo del animal para ver su ficha.");

        txtbuscar.setToolTipText("");
        txtbuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtbuscarKeyPressed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/buscar.png"))); // NOI18N
        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel10)
                        .addGap(18, 18, 18)
                        .addComponent(txtbuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 729, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(32, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(txtbuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 656, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(24, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-809)/2, (screenSize.height-773)/2, 809, 773);
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
   //chequearid(txtbuscar.getText());
    cargardatos();
    new Estadisticas(null, false).GenerarLineaCrecPeso(Integer.parseInt(txtbuscar.getText().trim()), lblChart, tablaPeso);
}//GEN-LAST:event_jButton1ActionPerformed

        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
            String identificacion = txtidentificacion.getText();
            String idsenasa = txtidsenasa.getText();
            String colorcaravana = combocolorcaravana.getSelectedItem().toString();
            String anionac = combonacimiento.getSelectedItem().toString();
            String numfuego = txtnumfuego.getText();
            String sexo;
            if (combosexo.getSelectedItem().toString().equals("Macho")) {
                sexo = "M";
            } else {
                sexo = "H";
            }

            int raza = comboraza.getSelectedIndex();
            int pelaje = combopelaje.getSelectedIndex();
            int procedencia = comboprocedencia.getSelectedIndex();
            String idmadre = txtidmadre.getText();
            int tipobovino = combotipobovino.getSelectedIndex();
            int cliente = combocliente.getSelectedIndex();
            int estado = comboestado.getSelectedIndex();
            String peso = txtpeso.getText();

            String consulta = "update bovino "
                    + "set anionacimiento='" + anionac + "', numerofuego='" + numfuego + "', sexo='" + sexo + "', idraza='" + raza + "', "
                    + "idpelaje='" + pelaje + "', idproveedor='" + procedencia + "', idmadre='" + idmadre + "', idtipobovino='" + tipobovino + "', "
                    + "idcliente='" + cliente + "', idestadoanimal='" + estado + "', NumSenasa='" + idsenasa + "', ColorCaravana='" + colorcaravana + "', Peso='" + peso + "' "
                    + "where identificacion='" + identificacion + "'";
            //System.out.println(consulta);

            try {
                Conectar();
                stmt.executeUpdate(consulta);
                JOptionPane.showMessageDialog(null, "Se modificaron los datos del animal exitosamente.", "Exito", JOptionPane.INFORMATION_MESSAGE);
                limpiarcampos();

            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Error al modificar los datos del animal. Por favor verifique los datos ingresados.", "Error", JOptionPane.ERROR_MESSAGE);
            }
    }//GEN-LAST:event_jButton2ActionPerformed

private void combonacimientoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combonacimientoActionPerformed
    Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    try {
        int edad = year - Integer.parseInt(combonacimiento.getSelectedItem().toString());

        if (edad == 1) {
            txtedad.setText(String.valueOf(edad) + " Año");
        } else {
            txtedad.setText(String.valueOf(edad) + " Años");
        }
    } catch (Exception e) {
    }
}//GEN-LAST:event_combonacimientoActionPerformed

    private void txtbuscarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtbuscarKeyPressed
        int k = (int) evt.getKeyChar();
        if (k == 10) {
            //transfiere el foco si presionas enter
            jButton1.doClick();
        }
    }//GEN-LAST:event_txtbuscarKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FichaAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FichaAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FichaAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FichaAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FichaAnimal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox combocliente;
    private javax.swing.JComboBox combocolorcaravana;
    private javax.swing.JComboBox comboestado;
    private javax.swing.JComboBox combonacimiento;
    private javax.swing.JComboBox combopelaje;
    private javax.swing.JComboBox comboprocedencia;
    private javax.swing.JComboBox comboraza;
    private javax.swing.JComboBox combosexo;
    private javax.swing.JComboBox combotipobovino;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel lblChart;
    private javax.swing.JTable tablaPeso;
    private javax.swing.JTable tablaenfermedades;
    private javax.swing.JTable tablaobservaciones;
    private javax.swing.JTable tablavacunacion;
    private javax.swing.JTextField txtbuscar;
    private javax.swing.JTextField txtedad;
    private javax.swing.JTextField txtfechaaplicacion;
    private javax.swing.JTextField txtidentificacion;
    private javax.swing.JTextField txtidmadre;
    private javax.swing.JTextField txtidsenasa;
    private javax.swing.JTextField txtidtag;
    private javax.swing.JTextField txtnumfuego;
    private javax.swing.JTextField txtpeso;
    // End of variables declaration//GEN-END:variables
    private conexion db;
    private Statement stmt;
    private String identificacion;

    public void Conectar() {
        try {
            db = new conexion();      //instancia de la clase conexion.java
            db.init();
            Connection conn = db.getMyConnection();
            stmt = conn.createStatement();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Problemas al concetarse a la Base de Datos", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void completarcomboraza() {
        String consulta = "Select descripcion from raza";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.beforeFirst();
            comboraza.addItem("-");
            while (rs.next()) {
                comboraza.addItem(rs.getString(1));
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar las razas", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void completarcombopelaje() {
        String consulta = "Select descripcion from pelaje";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.beforeFirst();
            combopelaje.addItem("-");
            while (rs.next()) {
                combopelaje.addItem(rs.getString(1));
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los pelajes", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void completarcomboprocedencia() {
        String consulta = "Select razonsocial from proveedor";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.beforeFirst();
            comboprocedencia.addItem("-");
            while (rs.next()) {
                comboprocedencia.addItem(rs.getString(1));
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los proveedores", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void completarcombotipo() {
        String consulta = "Select descripcion from tipobovino";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.beforeFirst();
            combotipobovino.addItem("-");
            while (rs.next()) {
                combotipobovino.addItem(rs.getString(1));
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los tipos de bovino", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void completarcombocliente() {
        String consulta = "Select razonsocial from cliente";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.beforeFirst();
            combocliente.addItem("-");
            while (rs.next()) {
                combocliente.addItem(rs.getString(1));
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los clientes", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void completarcomboestado() {
        String consulta = "Select descripcion from estadoanimal";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.beforeFirst();
            comboestado.addItem("-");
            while (rs.next()) {
                comboestado.addItem(rs.getString(1));
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los estados del animal", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void completarcomboaños() {
        int anioactual = 1960;
        Calendar c1 = Calendar.getInstance();
        int anio = c1.get(Calendar.YEAR);
        while (anioactual <= anio) {
            combonacimiento.addItem(anioactual);
            anioactual++;
        }
        combonacimiento.setSelectedIndex(-1);
    }

    private void completarvacunacion() {
        //String consulta = "Select b.identificacion, b.numerofuego, b.fechaaplicacion, b.sexo, b.anionacimiento, r.descripcion as 'Raza', tb.descripcion as 'Categoria' from  bovino b,raza r, tipobovino tb, estadoanimal ea where ea.idestadoanimal <> '2' and ea.idestadoanimal=b.idestadoanimal and b.idraza=r.idraza and b.idtipobovino=tb.idtipobovino";
        String consulta = "Select v.fecha as 'Fecha', v.identificacion as 'ID Senasa', t.descripcion as 'Tipo Vacunacion' from vacunacion v, tipovacunacion t where identificacion = '" + txtbuscar.getText() + "' and v.idtipovacunacion=t.idtipovacunacion order by fecha";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);

            DefaultTableModel modelo = new DefaultTableModel();
            tablavacunacion.setModel(modelo);
            ConversorRSaDefaultTableModel.completar(rs, modelo);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar las vacunaciones del animal", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    /*
    private void completarpeso() {
    String consulta = "Select fecha as 'Fecha', identificacion as 'ID Senasa', peso as 'Peso' from controlpeso where identificacion = '" + txtbuscar.getText() + "' order by fecha";
    try {
    Conectar();
    ResultSet rs = stmt.executeQuery(consulta);
    
    DefaultTableModel modelo = new DefaultTableModel();
    tablapeso.setModel(modelo);
    ConversorRSaDefaultTableModel.completar(rs, modelo);
    
    } catch (Exception ex) {
    JOptionPane.showMessageDialog(null, "Error al cargar el control de peso del animal", "Error", JOptionPane.ERROR_MESSAGE);
    }
    }*/

    private void completarenfermedades() {
        String consulta = "Select e.fecha as 'Fecha', t.descripcion as 'Enfermedad', e.observacion as 'Observaciones' from enfermedad e, tipoenfermedad t where identificacion = '" + txtbuscar.getText() + "' and e.idtipoenfermedad=t.idtipoenfermedad order by fecha";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);

            DefaultTableModel modelo = new DefaultTableModel();
            tablaenfermedades.setModel(modelo);
            ConversorRSaDefaultTableModel.completar(rs, modelo);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar las enfermedades del animal", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void completarobservaciones() {
        String consulta = "Select fecha as 'Fecha', descripcion as 'Descripcion' from observaciones where identificacion = '" + txtbuscar.getText() + "' order by fecha desc";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);

            DefaultTableModel modelo = new DefaultTableModel();
            tablaobservaciones.setModel(modelo);
            ConversorRSaDefaultTableModel.completar(rs, modelo);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar las Observaciones del animal", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void chequearid(String identif) {
        String ultimoid = "Select MAX(identificacion) as Id from bovino "
                + "where idtag = (Select idtag from bovino where identificacion = '" + identif + "')";
        try {
            Conectar();
            ResultSet r = stmt.executeQuery(ultimoid);
            if (r.first()) {
                String id = r.getString("Id");
                if (!id.equals(identif)) {
                    identificacion = id;
                    JOptionPane.showMessageDialog(null, "El animal ingresado con identificación " + identif + " no se encuentra dentro de los animales registrados. \n "
                            + "Se cargarán los datos correspondientes al animal con identificacion " + identificacion + " debido a que este posee el chip que correspondía a " + identif + " ", "Aviso", JOptionPane.CLOSED_OPTION);

                } else {
                    identificacion = identif;
                }
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los datos del animal", "Error", JOptionPane.ERROR_MESSAGE);
        }

    }

    private void cargardatos() {
        identificacion = txtbuscar.getText();
        String consulta = "Select * from bovino where idjose = '" + identificacion + "'";
        int i = 0;
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.last();
            System.out.println(rs.getRow());
            if (rs.getRow() == 0) {
                JOptionPane.showMessageDialog(null, "No existe ningun animal con ese codigo. Por favor verifique el dato ingresado. ", "Error", JOptionPane.ERROR_MESSAGE);
                limpiarcampos();
            } else {
                rs.beforeFirst();
                while (rs.next()) {
                    txtidentificacion.setText(rs.getString("idjose"));
                    txtidsenasa.setText(rs.getString("NumSenasa"));
                    txtidtag.setText(rs.getString("idtag"));

                    String[] fecha = rs.getString("fechaaplicacion").split("-");
                    txtfechaaplicacion.setText(fecha[2].toString() + "/" + fecha[1].toString() + "/" + fecha[0].toString());
                    //JFormattedTextField textField = new JFormattedTextField(new FormatoFecha());
                    //textField.setValue(new Date());

                    String color = rs.getString("ColorCaravana");
                    System.out.println(color);
                    if (color.equals("Verde")) {
                        combocolorcaravana.setSelectedIndex(0);
                    } else if (color.equals("Naranja")) {
                        combocolorcaravana.setSelectedIndex(1);
                    } else if (color.equals("Amarillo")) {
                        combocolorcaravana.setSelectedIndex(2);
                    } else if (color.equals("Roja")) {
                        combocolorcaravana.setSelectedIndex(3);
                    } else if (color.equals("Blanca")) {
                        combocolorcaravana.setSelectedIndex(4);
                    } else if (color.equals("Celeste")) {
                        combocolorcaravana.setSelectedIndex(5);
                    }
                    String anio = rs.getString("anionacimiento");
                    //System.out.println(anio);
                    while (i < combonacimiento.getItemCount()) {
                        String seleccionado = String.valueOf(combonacimiento.getItemAt(combonacimiento.getSelectedIndex()));
                        //System.out.println(seleccionado);
                        if (anio.equals(seleccionado)) {
                            break;
                        } else {
                            combonacimiento.setSelectedIndex(i++);
                        }
                    }
                    Calendar c1 = Calendar.getInstance();
                    int year = c1.get(Calendar.YEAR);
                    int edad = year - Integer.parseInt(combonacimiento.getSelectedItem().toString());
                    if (edad == 1) {
                        txtedad.setText(String.valueOf(edad) + " Año");
                    } else {
                        txtedad.setText(String.valueOf(edad) + " Años");
                    }

                    txtnumfuego.setText(rs.getString("numerofuego"));
                    if (rs.getString("sexo").equals("M")) {          //M = Macho, H=Hembra
                        combosexo.setSelectedIndex(0);
                    } else {
                        combosexo.setSelectedIndex(1);
                    }
                    comboraza.setSelectedIndex(rs.getInt("idraza"));
                    combopelaje.setSelectedIndex(rs.getInt("idpelaje"));
                    comboprocedencia.setSelectedIndex(rs.getInt("idproveedor"));
                    txtidmadre.setText(rs.getString("idmadre"));
                    combotipobovino.setSelectedIndex(rs.getInt("idtipobovino"));
                    combocliente.setSelectedIndex(rs.getInt("idcliente"));
                    comboestado.setSelectedIndex(rs.getInt("idestadoanimal"));
                    txtpeso.setText(rs.getString("Peso"));
                }

                //Metodo para completar la ficha "Vacunaciones"
                completarvacunacion();

                //Metodo para completar la ficha "Control de Peso"


                //Metodo para completar la ficha "Historial de Enfermedades"
                completarenfermedades();

                //Metodo para completar la ficha "Observaciones"
                completarobservaciones();
            }



        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los datos del animal", "Error", JOptionPane.ERROR_MESSAGE);
        }

    }

    private void limpiarcampos() {
        //limpia los campos del formulario
        txtbuscar.setText("");
        txtidentificacion.setText("");
        txtidsenasa.setText("");
        txtidtag.setText("");
        txtfechaaplicacion.setText("");
        txtidmadre.setText("");
        txtnumfuego.setText("");
        txtedad.setText("");
        txtpeso.setText("");
        combocolorcaravana.setSelectedIndex(-1);
        combocliente.setSelectedIndex(0);
        comboestado.setSelectedIndex(0);
        combonacimiento.setSelectedIndex(-1);
        combopelaje.setSelectedIndex(0);
        comboprocedencia.setSelectedIndex(0);
        comboraza.setSelectedIndex(0);
        combosexo.setSelectedIndex(-1);
        combotipobovino.setSelectedIndex(0);

        //limpia los jtable
        LimpiarJTable.reiniciarJTable(tablaenfermedades);
        LimpiarJTable.reiniciarJTable(tablaobservaciones);
//        LimpiarJTable.reiniciarJTable(tablapeso);
        LimpiarJTable.reiniciarJTable(tablavacunacion);
    }
}
